import axios from 'axios';
import { domain } from './config'
// 移除顶层的 store 导入和初始化
// import { useMainStore } from '@/stores/useMain';
// const mainStore = useMainStore();

const defaultConfig = {
  baseURL: domain || '', // 使用环境变量
  timeout: 50000,
};

class Http {
  constructor() {
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }
 
  static axiosInstance = axios.create(defaultConfig);

  // 修改请求拦截器，在运行时获取 store
  httpInterceptorsRequest() {
    Http.axiosInstance.interceptors.request.use(
      async (config) => {
        try {
          const storeModule = await import('@/stores/useMain');
          const mainStore = storeModule.useMainStore();
          if (mainStore?.token) {
            config.headers['token'] = mainStore.token;
          }
        } catch (storeError) {
          console.warn('Failed to get token from store', storeError);
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  httpInterceptorsResponse() {
    Http.axiosInstance.interceptors.response.use(
      (response) => response.data,
      (error) => {
        if (error.response) {
          // 根据不同的状态码做相应处理
          switch (error.response.status) {
            case 401:
              console.error('未授权');
              break;
            case 500:
              console.error('服务器内部错误');
              break;
            // 更多状态码...
            default:
              console.error(`请求出错: ${error.message}`);
          }
        }
        return Promise.reject(error);
      }
    );
  }

  request(config) {
    return Http.axiosInstance.request(config);
  }

  get(config) {
    return this.request({ ...config, method: 'get' });
  }

  post(config) {
    return this.request({ ...config, method: 'post' });
  }

  put(config) {
    return this.request({ ...config, method: 'put' });
  }

  delete(config) {
    return this.request({ ...config, method: 'delete' });
  }

  patch(config) {
    return this.request({ ...config, method: 'patch' });
  }
}

export default new Http();